/**
 * 卡片扩展模块，提供卡片创建、销毁、刷新等生命周期回调
 *
 * 卡片生命周期管理文件
 */
import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';

const TAG: string = "EntryFormAbility--"

export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want) {
    // Called to return a FormBindingData object.

    // 在入参want中可以取出卡片的唯一标识：formId
    let formId: string = want.parameters[formInfo.FormParam.IDENTITY_KEY];

    // 使用方创建卡片时触发，提供方需要返回卡片数据绑定类
    let formData = {
      "formId": formId,
      "title": "初次赋值",
      "message": "初次message"
    };
    return formBindingData.createFormBindingData(formData);
  }

  onCastToNormalForm(formId) {
    // Called when the form provider is notified that a temporary form is successfully
    // converted to a normal form.

    // 使用方将临时卡片转换为常态卡片触发，提供方需要做相应的处理
    console.info(TAG, `[EntryFormAbility] onCastToNormalForm, formId: ${formId}`);
  }

  onUpdateForm(formId) {
    // Called to notify the form provider to update a specified form.

    // 若卡片支持定时更新/定点更新/卡片使用方主动请求更新功能，则提供方需要重写该方法以支持数据更新
    console.info(TAG, '[EntryFormAbility] onUpdateForm');
  }

  onChangeFormVisibility(newStatus) {
    // Called when the form provider receives form events from the system.

    // 需要配置formVisibleNotify为true，且为系统应用才会回调
    console.info(TAG, '[EntryFormAbility] onChangeFormVisibility');
  }

  onFormEvent(formId, message) {
    // Called when a specified message event defined by the form provider is triggered.

    // 若卡片支持触发事件，则需要重写该方法并实现对事件的触发
    console.info(TAG, '[EntryFormAbility] onFormEvent');
    console.info(TAG, `FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);

    // 处理卡片刷新
    let formData = {
      title: "微信卡片",
      message: "我现在可以接受微信消息展示啦，随时关注消息提醒，不会错过任何信息哦"
    }
    let formInfo = formBindingData.createFormBindingData(formData)
    formProvider.updateForm(formId, formInfo).then((data) => {
      console.info(TAG, 'FormAbility updateForm success.' + JSON.stringify(data));
    }).catch((error) => {
      console.error(TAG, 'FormAbility updateForm failed: ' + JSON.stringify(error));
    })
  }

  onRemoveForm(formId) {
    // Called to notify the form provider that a specified form has been destroyed.

    // 当对应的卡片删除时触发的回调，入参是被删除的卡片ID
    console.info(TAG, '[EntryFormAbility] onRemoveForm');
  }

  onConfigurationUpdate(config) {
    // 当系统配置信息置更新时触发的回调
    console.info(TAG, '[EntryFormAbility] configurationUpdate:' + JSON.stringify(config));
  }

  onAcquireFormState(want) {
    // Called to return a {@link FormState} object.
    // 卡片提供方接收查询卡片状态通知接口，默认返回卡片初始状态。
    return formInfo.FormState.READY;
  }
};